package network.server.handler.StoreHandler;

import common.model.Entity.StoreEntity.Order;
import module.StoreService.Impl.ProductServiceImpl;
import module.StoreService.OrderService;
import module.StoreService.Impl.OrderServiceImpl;
import network.protocol.Request;
import network.protocol.Response;
import network.server.RequestHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * {@code OrderHandler} 是订单相关请求的处理器，实现了 {@link RequestHandler} 接口。
 * <p>
 * 功能概述：
 * <ul>
 *     <li>接收并解析客户端请求</li>
 *     <li>根据 action 中的操作类型调用 {@link OrderService}</li>
 *     <li>返回统一的 {@link Response} 封装结果</li>
 * </ul>
 * <p>
 * 支持的操作：
 * <ul>
 *     <li>{@code getOrderById} - 根据订单 ID 获取订单</li>
 *     <li>{@code getOrderByNumber} - 根据订单号获取订单</li>
 *     <li>{@code getOrdersByUser} - 获取用户的所有订单</li>
 *     <li>{@code getOrdersByStatus} - 根据状态获取订单</li>
 *     <li>{@code getOrdersByUserAndStatus} - 根据用户和状态获取订单</li>
 *     <li>{@code getAllOrders} - 获取所有订单</li>
 *     <li>{@code createOrder} - 创建新订单</li>
 *     <li>{@code updateOrder} - 更新订单信息</li>
 *     <li>{@code deleteOrder} - 删除订单</li>
 *     <li>{@code updateOrderStatus} - 修改订单状态</li>
 *     <li>{@code getOrderCount} - 获取订单总数</li>
 *     <li>{@code getOrderCountByUser} - 获取某用户订单总数</li>
 * </ul>
 */
public class OrderHandler implements RequestHandler {
    private final OrderService orderService;
    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    /**
     * 构造函数，初始化时使用 {@link OrderServiceImpl#getInstance()} 获取单例服务对象。
     */
    public OrderHandler() {
        this.orderService = OrderServiceImpl.getInstance();
    }

    /**
     * 处理客户端请求，根据 action 映射到具体的订单操作方法。
     *
     * @param req 请求对象，包含 action 和参数
     * @return 响应对象，包含执行结果或错误信息
     */
    @Override
    public Response<?> handle(Request req) {
        String action = req.getAction();
        String methodName = action.substring(action.indexOf('.') + 1);
        Map<String, Object> params = req.getParams();

        try {
            switch (methodName) {
                case "getOrderById":
                    return handleGetOrderById(params);
                case "getOrderByNumber":
                    return handleGetOrderByNumber(params);
                case "getOrdersByUser":
                    return handleGetOrdersByUser(params);
                case "getOrdersByStatus":
                    return handleGetOrdersByStatus(params);
                case "getOrdersByUserAndStatus":
                    return handleGetOrdersByUserAndStatus(params);
                case "getAllOrders":
                    return orderService.getAllOrders();
                case "createOrder":
                    return handleCreateOrder(params);
                case "updateOrder":
                    return handleUpdateOrder(params);
                case "deleteOrder":
                    return handleDeleteOrder(params);
                case "updateOrderStatus":
                    return handleUpdateOrderStatus(params);
                case "getOrderCount":
                    return orderService.getOrderCount();
                case "getOrderCountByUser":
                    return handleGetOrderCountByUser(params);
                default:
                    return Response.error("未知操作: " + methodName);
            }
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误: " + e.getMessage());
        } catch (Exception e) {
            return Response.error("处理请求时发生错误: " + e.getMessage());
        }
    }

    /**
     * 根据订单 ID 获取订单。
     *
     * @param params 请求参数，必须包含 {@code id}
     * @return 订单对象或错误信息
     */
    private Response<?> handleGetOrderById(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }
        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());
            return orderService.getOrderById(id);
        } catch (NumberFormatException e) {
            return Response.error("id参数格式错误");
        }
    }

    /**
     * 根据订单号获取订单。
     *
     * @param params 请求参数，必须包含 {@code orderNumber}
     * @return 订单对象或错误信息
     */
    private Response<?> handleGetOrderByNumber(Map<String, Object> params) {
        if (!params.containsKey("orderNumber")) {
            return Response.error("缺少必要参数: orderNumber");
        }
        Object orderNumberObj = params.get("orderNumber");
        if (orderNumberObj == null) {
            return Response.error("orderNumber参数不能为null");
        }
        String orderNumber = orderNumberObj.toString();
        return orderService.getOrderByNumber(orderNumber);
    }

    /**
     * 根据用户 ID 获取订单。
     *
     * @param params 请求参数，必须包含 {@code userId}
     * @return 订单列表或错误信息
     */
    private Response<?> handleGetOrdersByUser(Map<String, Object> params) {
        if (!params.containsKey("userId")) {
            return Response.error("缺少必要参数: userId");
        }
        try {
            Object userIdObj = params.get("userId");
            if (userIdObj == null) {
                return Response.error("userId参数不能为null");
            }
            long userId = Long.parseLong(userIdObj.toString());
            return orderService.getOrdersByUser(userId);
        } catch (NumberFormatException e) {
            return Response.error("userId参数格式错误");
        }
    }

    /**
     * 根据订单状态获取订单。
     *
     * @param params 请求参数，必须包含 {@code status}
     * @return 订单列表或错误信息
     */
    private Response<?> handleGetOrdersByStatus(Map<String, Object> params) {
        if (!params.containsKey("status")) {
            return Response.error("缺少必要参数: status");
        }
        try {
            Object statusObj = params.get("status");
            if (statusObj == null) {
                return Response.error("status参数不能为null");
            }
            int status = Integer.parseInt(statusObj.toString());
            return orderService.getOrdersByStatus(status);
        } catch (NumberFormatException e) {
            return Response.error("status参数格式错误");
        }
    }

    /**
     * 根据用户 ID 和状态获取订单。
     *
     * @param params 请求参数，必须包含 {@code userId}, {@code status}
     * @return 订单列表或错误信息
     */
    private Response<?> handleGetOrdersByUserAndStatus(Map<String, Object> params) {
        if (!params.containsKey("userId") || !params.containsKey("status")) {
            return Response.error("缺少必要参数: userId 或 status");
        }
        try {
            Object userIdObj = params.get("userId");
            if (userIdObj == null) {
                return Response.error("userId参数不能为null");
            }
            long userId = Long.parseLong(userIdObj.toString());

            Object statusObj = params.get("status");
            if (statusObj == null) {
                return Response.error("status参数不能为null");
            }
            int status = Integer.parseInt(statusObj.toString());
            return orderService.getOrdersByUserAndStatus(userId, status);
        } catch (NumberFormatException e) {
            return Response.error("userId或status参数格式错误");
        }
    }

    /**
     * 创建订单。
     *
     * @param params 请求参数，必须包含 {@code userId}, {@code orderNumber}, {@code totalAmount}, {@code status}
     * @return 创建结果，包含订单 ID 或错误信息
     */
    private Response<?> handleCreateOrder(Map<String, Object> params) {
        if (!params.containsKey("userId") ||
                !params.containsKey("orderNumber") ||
                !params.containsKey("totalAmount") ||
                !params.containsKey("status")) {
            return Response.error("缺少必要参数: userId, orderNumber, totalAmount, status");
        }
        try {
            Order order = new Order();
            order.setUserId(Long.parseLong(params.get("userId").toString()));
            order.setOrderNumber(params.get("orderNumber").toString());
            order.setTotalAmount(Double.parseDouble(params.get("totalAmount").toString()));
            order.setStatus(Integer.parseInt(params.get("status").toString()));

            Response<?> resp = orderService.createOrder(order);
            if (!resp.isSuccess()) {
                return resp;
            }

            Long orderId = order.getId();
            if (orderId == null) {
                logger.error("订单创建后主键未回填，请检查 insert 语句配置");
                return Response.error("订单创建后无法获取主键");
            }

            Map<String, Object> respMap = new HashMap<>();
            respMap.put("orderId", order.getId());
            return Response.success(respMap);

        } catch (NumberFormatException e) {
            return Response.error("参数格式错误");
        } catch (Exception e) {
            logger.error("创建订单异常", e);
            return Response.error("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 更新订单。
     *
     * @param params 请求参数，必须包含 {@code id}，可选 {@code totalAmount}, {@code status}
     * @return 更新结果
     */
    private Response<?> handleUpdateOrder(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }
        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());

            Response<Optional<Order>> response = orderService.getOrderById(id);
            if (!response.isSuccess() || response.getData().isEmpty()) {
                return Response.error("未找到指定订单");
            }
            Order order = response.getData().get();

            if (params.containsKey("totalAmount")) {
                Object totalAmountObj = params.get("totalAmount");
                if (totalAmountObj != null) {
                    order.setTotalAmount(Double.parseDouble(totalAmountObj.toString()));
                }
            }
            if (params.containsKey("status")) {
                Object statusObj = params.get("status");
                if (statusObj != null) {
                    order.setStatus(Integer.parseInt(statusObj.toString()));
                }
            }
            return orderService.updateOrder(order);
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误");
        }
    }

    /**
     * 删除订单。
     *
     * @param params 请求参数，必须包含 {@code id}
     * @return 删除结果
     */
    private Response<?> handleDeleteOrder(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }
        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());
            return orderService.deleteOrder(id);
        } catch (NumberFormatException e) {
            return Response.error("id参数格式错误");
        }
    }

    /**
     * 更新订单状态。
     *
     * @param params 请求参数，必须包含 {@code orderId}, {@code status}
     * @return 更新结果
     */
    private Response<?> handleUpdateOrderStatus(Map<String, Object> params) {
        if (!params.containsKey("orderId") || !params.containsKey("status")) {
            return Response.error("缺少必要参数: orderId 或 status");
        }
        try {
            Object orderIdObj = params.get("orderId");
            if (orderIdObj == null) {
                return Response.error("orderId参数不能为null");
            }
            long orderId = Long.parseLong(orderIdObj.toString());

            Object statusObj = params.get("status");
            if (statusObj == null) {
                return Response.error("status参数不能为null");
            }
            int status = Integer.parseInt(statusObj.toString());

            return orderService.updateOrderStatus(orderId, status);
        } catch (NumberFormatException e) {
            return Response.error("orderId或status参数格式错误");
        }
    }

    /**
     * 获取某个用户的订单总数。
     *
     * @param params 请求参数，必须包含 {@code userId}
     * @return 订单数量
     */
    private Response<?> handleGetOrderCountByUser(Map<String, Object> params) {
        if (!params.containsKey("userId")) {
            return Response.error("缺少必要参数: userId");
        }
        try {
            Object userIdObj = params.get("userId");
            if (userIdObj == null) {
                return Response.error("userId参数不能为null");
            }
            long userId = Long.parseLong(userIdObj.toString());
            return orderService.getOrderCountByUser(userId);
        } catch (NumberFormatException e) {
            return Response.error("userId参数格式错误");
        }
    }
}
